using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FirebirdSql.Data.FirebirdClient;
using FirebirdSql.Data.Isql;
using System.Data;

namespace Pg.BioMedics.RatObserver.Database.DAO.Impl
{
    abstract class BaseDAO
    {
        protected static String DATABASE_FILE = "data.fdb";
        private static FbConnection c;
        private static FbConnectionStringBuilder csb;

        static BaseDAO()
        {
            csb = new FbConnectionStringBuilder();
            csb.ServerType = FbServerType.Embedded; // we are using the embedded Firebird
            csb.UserID = "SYSDBA";
            csb.Password = "masterkey";
            csb.Dialect = 3;
            csb.Database = DATABASE_FILE;
        }

        private static Boolean databaseExists()
        {
            return File.Exists(DATABASE_FILE);
        }

        private void createDatabaseAndConnect()
        {
            FbConnection.CreateDatabase(csb.ToString());
            c = new FbConnection(csb.ToString());
            connect();

            // parse the SQL script
            FbScript script = new FbScript("c:\\initdb.sql");
            script.Parse();

            // execute the SQL script

                FbBatchExecution fbe = new FbBatchExecution(c);
                foreach (string cmd in script.Results)
                {
                    fbe.SqlStatements.Add(cmd);
                }
                fbe.Execute();

        }

        private void connect()
        {
            if (c == null)
                c = new FbConnection(csb.ToString());
            c.Open();
        }

        protected FbConnection getConnection()
        {
            if (c == null)
            {
                if (databaseExists())
                    connect();
                else
                {
                    createDatabaseAndConnect();
                }
            }
            return c;
        }
    }
}
